package com.agileai.bpm.controller.define;

import java.util.List;

import org.codehaus.jettison.json.JSONObject;

import com.agileai.bpm.bizmoduler.define.WfProcessManage;
import com.agileai.bpm.common.ProcessDefineHelper;
import com.agileai.bpm.model.ProcessDefineDocument;
import com.agileai.common.KeyGenerator;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.bizmoduler.frame.SecurityAuthorizationConfig;
import com.agileai.hotweb.controller.core.BaseHandler;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.util.DateUtil;
import com.agileai.util.StringUtil;

public class WfProcessDefineEditHandler extends BaseHandler{
	public static final String ProcessDefineSessionKey = "ProcessDefineKey";
	
	public ViewRenderer prepareDisplay(DataParam param){
		this.setAttribute("WFP_ID",param.get("WFP_ID"));
		return new LocalRenderer(getPage());
	}
	
	@PageAction
	public ViewRenderer retrieveJsonData(DataParam param){
		WfProcessManage manage = this.getService();
		DataRow row = manage.getRecord(param);
		String responseText = row.getString("WFP_GRAPH");
		String processDefine = row.getString("WFP_DEFINE");
		
		try {
			ProcessDefineDocument processDefineDocument = ProcessDefineDocument.Factory.parse(processDefine);
			this.getSessionAttributes().put(ProcessDefineSessionKey, processDefineDocument);
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
	
	@PageAction
	public ViewRenderer createActivity(DataParam param){
		String responseText = FAIL;
		try {
			String processId = param.get("processId");
			String activityType = param.get("activityType");
			String activityCode = param.get("activityCode");
			String tempJson = param.get("tempJson");
			String activityId = KeyGenerator.instance().genKey();
			
			WfProcessManage wfProcessManage = this.getService();
			wfProcessManage.createActivity(processId, activityId, activityCode, activityType);

			JSONObject jsonObject = new JSONObject(tempJson);
			ProcessDefineDocument processDefineDocument = (ProcessDefineDocument)this.getSessionAttribute(ProcessDefineSessionKey);
			ProcessDefineHelper processHelper = new ProcessDefineHelper();
			JSONObject props = jsonObject.getJSONObject("props");
			String defaultActivityName = props.getJSONObject("text").getString("value"); 
			processHelper.createActivity(processDefineDocument,activityId,activityType,activityCode,defaultActivityName);
			
			wfProcessManage.updatePorcessDefine(processId, processDefineDocument.toString(),null);
			
			String objectIndex = param.get("objectIndex");
			jsonObject.getJSONObject("props").put("key",new DataRow("value",activityId));
			jsonObject.getJSONObject("props").put("code",new DataRow("value","rect"+objectIndex));
			
			responseText = jsonObject.toString();
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
	
	@PageAction
	public ViewRenderer saveProccessDefine(DataParam param){
		String responseText = FAIL;
		try {
			String processJson = param.get("processJson");
			
			User user = (User)getUser();
			DataRow record = getService().getRecord(param);
			DataParam newParam = record.toDataParam(true);
			newParam.update(param);
			newParam.put("WFP_MODIFY_TIME", DateUtil.getDateByType(DateUtil.YYMMDDHHMI_HORIZONTAL));
			newParam.put("WFP_MODIFIER", user.getUserId());
			
			if (!StringUtil.isNullOrEmpty(processJson)){
				JSONObject jsonObject = new JSONObject(processJson);
				newParam.put("WFP_GRAPH", jsonObject.toString());
			}
			ProcessDefineDocument processDefineDocument = (ProcessDefineDocument)this.getSessionAttribute(ProcessDefineSessionKey);
			if (processDefineDocument != null){
				newParam.put("WFP_DEFINE", processDefineDocument.toString());					
			}
			getService().updateRecord(newParam);	
			responseText = SUCCESS;
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
	
	@PageAction
	public ViewRenderer createTransition(DataParam param){
		String responseText = FAIL;
		try {
			String processId = param.get("processId");
			String transitionCode = param.get("transitionCode");
			String fromActivityCode = param.get("fromActivityCode");
			String toActivityCode = param.get("toActivityCode");
			String transitionId = KeyGenerator.instance().genKey();
			
			ProcessDefineDocument processDefineDocument = (ProcessDefineDocument)this.getSessionAttribute(ProcessDefineSessionKey);
			ProcessDefineHelper defineHelper = new ProcessDefineHelper();
			String fromActivityId = defineHelper.retreiveActivityId(processDefineDocument, fromActivityCode);
			String toActivityId = defineHelper.retreiveActivityId(processDefineDocument, toActivityCode);
			defineHelper.createTransition(processDefineDocument, transitionId, transitionCode, fromActivityId,toActivityId);

			WfProcessManage wfProcessManage = this.getService();
			wfProcessManage.createTransition(processId, transitionId,transitionCode,fromActivityId, toActivityId);
			wfProcessManage.updatePorcessDefine(processId, processDefineDocument.toString(),null);
			
			String objectIndex = param.get("objectIndex");
			String tempJson = param.get("tempJson");
			JSONObject jsonObject = new JSONObject(tempJson);
			jsonObject.getJSONObject("props").put("key",new DataRow("value",transitionId));
			jsonObject.getJSONObject("props").put("code",new DataRow("value","path"+objectIndex));
			
			responseText = jsonObject.toString();
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}	
	
	@PageAction
	public ViewRenderer deleteActivity(DataParam param){
		String responseText = FAIL;
		try {
			String processId = param.get("processId");
			String tempJson = param.get("tempJson");
			JSONObject jsonObject = new JSONObject(tempJson);
			String activityId = jsonObject.getJSONObject("props").getJSONObject("key").getString("value");
			
			SecurityAuthorizationConfig securityAuthorizationConfig = (SecurityAuthorizationConfig)this.lookupService("securityAuthorizationConfigService");
			securityAuthorizationConfig.delUserAuthRelations("Activity", activityId);
			securityAuthorizationConfig.delRoleAuthRelations("Activity", activityId);
			securityAuthorizationConfig.delGroupAuthRelations("Activity", activityId);
			
			ProcessDefineDocument processDefineDocument = (ProcessDefineDocument)this.getSessionAttribute(ProcessDefineSessionKey);
			ProcessDefineHelper defineHelper = new ProcessDefineHelper();
			List<String> transitionIds = defineHelper.retrieveTransitionIdList(processDefineDocument, activityId);
			defineHelper.deleteActivity(processDefineDocument, activityId);

			WfProcessManage wfProcessManage = this.getService();
			wfProcessManage.deleteActivity(processId, activityId, transitionIds);
			wfProcessManage.updatePorcessDefine(processId, processDefineDocument.toString(),null);
			
			responseText = SUCCESS;
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
	
	@PageAction
	public ViewRenderer deleteTransition(DataParam param){
		String responseText = FAIL;
		try {
			String processId = param.get("processId");
			String tempJson = param.get("tempJson");
			JSONObject jsonObject = new JSONObject(tempJson);
			String transitionId = jsonObject.getJSONObject("props").getJSONObject("key").getString("value");
			
			ProcessDefineDocument processDefineDocument = (ProcessDefineDocument)this.getSessionAttribute(ProcessDefineSessionKey);
			ProcessDefineHelper defineHelper = new ProcessDefineHelper();
			defineHelper.deleteTransition(processDefineDocument, transitionId);
			
			WfProcessManage wfProcessManage = this.getService();
			wfProcessManage.deleteTransition(processId, transitionId);
			wfProcessManage.updatePorcessDefine(processId, processDefineDocument.toString(),null);
			
			responseText = SUCCESS;
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
	
	protected WfProcessManage getService() {
		return (WfProcessManage)this.lookupService(WfProcessManage.class);
	}
}